<template>
  <view class="map container">
    <!-- Search Header -->
    <view class="search-header" :style="{ top: geStatusBarHeight() + getNavBarHeight() + 'px', overflow: overflow }">
      <view class="search-header-top">
        <view class="location" @click="changeCity">
          <text>{{ currentCity.name }}</text>
          <u-icon style="margin: 0 12rpx" size="24rpx" name="arrow-down-fill"></u-icon>
        </view>
        <view class="search-box">
          <u-search
              placeholder="搜索充电站"
              :show-action="true"
              :disabled="false"
              @click="toSearch"
              @custom="handleSearch"
          />
        </view>
        <view class="message" @click="toNotice">
          <image src="/static/map/msg.png" alt="" style="width: 40rpx;height: 40rpx;margin-left: 6rpx"/>
          <text class="badge">{{ messageCount }}</text>
        </view>
      </view>
      <div class="filter-box">
        <u-dropdown active-color="#1296db" @open="open" @close="close">
          <u-dropdown-item
              @change="initMap"
              v-model="searchForm.sortType" :title="formatSearchForm.sortTypeLabel || '综合排序'" :options="options1"></u-dropdown-item>
          <u-dropdown-item
              @change="initMap"
              v-model="searchForm.distance" :title="formatSearchForm.distanceLabel || '距离'" :options="options2"></u-dropdown-item>
          <u-dropdown-item
              @change="initMap"
              v-model="searchForm.speedType" :title="formatSearchForm.speedTypeLabel || '充电速度'" :options="options3"></u-dropdown-item>
        </u-dropdown>
      </div>
    </view>

    <!-- Map Container -->
    <view class="map-container">
      <map
        v-if="isShowMap && mapCenter"
        id="map"
        class="map"
        :latitude="mapCenter.latitude"
        :longitude="mapCenter.longitude"
        :markers="markers"
        :scale="scale"
        show-location
        @markertap="handleMarkerTap"
        @callouttap="handleMarkerTap"
      ></map>

      <!-- Map Controls -->
      <view class="map-controls" :style="{ bottom: selectedStation ? '500rpx' : '280rpx'}">
        <view class="control-btn" @tap="zoomIn">
          <image src="/static/map/plus.png" ></image>
        </view>
        <view class="control-btn" @tap="zoomOut">
          <image src="/static/map/minus.png" ></image>
        </view>
        <view class="control-btn" @tap="moveToLocation">
          <image src="/static/map/location.png" ></image>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import Page from "../../components/Page.vue";

export default {
  components: {Page},
  data() {
    return {
      overflow: 'hidden',
      searchForm: {
        sortType: 1,
        distance: '',
        speedType: '',
      },
      options1: [
        {
          label: '综合排序',
          value: 1,
        },
        {
          label: '离我最近',
          value: 2,
        },
        {
          label: '价格最低',
          value: 3,
        },
        {
          label: '空闲最多',
          value: 4,
        },
      ],
      options2: [
        // 1km 2km 3km 4km 5km
        {
          label: '全部',
          value: '',
        },
        {
          label: '1km',
          value: 1,
        },
        {
          label: '2km',
          value: 2,
        },
        {
          label: '3km',
          value: 3,
        },
        {
          label: '4km',
          value: 4,
        },
        {
          label: '5km',
          value: 5,
        },
        // 10km 20km 30km 40km 50km
        {
          label: '10km',
          value: 10,
        },
        {
          label: '20km',
          value: 20,
        },
        {
          label: '30km',
          value: 30,
        },
        {
          label: '40km',
          value: 40,
        },
        {
          label: '50km',
          value: 50,
        },
      ],
      options3: [
        {
          label: '快充',
          value: 1,
        },
        {
          label: '慢充',
          value: 0,
        },
      ],
      keyword: '',
      // 用户当前位置（用于计算距离）
      location: null,
      // 地图中心位置（用于显示地图）
      mapCenter: null,
      markers: [],
      selectedStation: null,
      messageCount: 0,
      stations: [],
      currentCity: {
        name: '定位中...',
        code: ''
      },
      scale: 16,
      mapContext: null,
      isShowMap: false
    }
  },
  onLoad() {
    // 监听城市选择事件
    uni.$on('citySelected', this.handleCitySelected)

    // 获取存储的城市
    const savedCity = uni.getStorageSync('selectedCity')

    // 如果有缓存的城市，优先使用缓存的城市信息
    if (savedCity && savedCity.name !== '定位中...') {
      this.currentCity = savedCity
      // 使用地理编码获取保存城市的经纬度
      uni.request({
        url: `/ws/geocoder/v1/?address=${encodeURIComponent(savedCity.name)}&key=VQKBZ-WWSLG-EJQQI-IFK6O-E7CC6-N2BQE`,
        success: (res) => {
          if (res.data.status === 0) {
            const location = res.data.result.location
            // 设置地图中心点为城市坐标
            this.mapCenter = {
              latitude: location.lat,
              longitude: location.lng
            }
            // 初始化地图并获取数据
            this.isShowMap = true
            this.$nextTick(() => {
              this.mapContext = uni.createMapContext('map', this)
              this.initMap()
            })
          }
        },
        fail: () => {
          // 如果解析缓存城市失败，尝试获取当前位置
          this.getCurrentLocation()
        }
      })
    } else {
      // 如果没有缓存的城市，获取当前位置
      this.getCurrentLocation()
    }
  },
  onUnload() {
    // 移除事件监听
    uni.$off('citySelected', this.handleCitySelected)
  },
  computed: {
    formatSearchForm() {
      let distance = ''
      let sortType = ''
      let speedType = ''
      let distanceLabel = ''
      let sortTypeLabel = ''
      let speedTypeLabel = ''
      let findDistance = this.options2.find(item => item.value === this.searchForm.distance)
      if (findDistance) {
        distance = findDistance.value
        distanceLabel = findDistance.label
      }
      let findSortType = this.options1.find(item => item.value === this.searchForm.sortType)
      if (findSortType) {
        sortType = findSortType.value
        sortTypeLabel = findSortType.label
      }
      let findSpeedType = this.options3.find(item => item.value === this.searchForm.speedType)
      if (findSpeedType) {
        speedType = findSpeedType.value
        speedTypeLabel = findSpeedType.label
      }
      return {
        distance,
        distanceLabel,
        sortType,
        sortTypeLabel,
        speedType,
        speedTypeLabel
      }
    }
  },
  methods: {
    // 获取状态栏高度
    geStatusBarHeight(){
      // #ifdef MP-WEIXIN
      return uni.getSystemInfoSync().statusBarHeight
      // #endif
      // #ifdef H5
      return 0
      // #endif
    },
    // 获取导航栏高度
    getNavBarHeight(){
      // #ifdef MP-WEIXIN
      const menuButtonInfo = uni.getMenuButtonBoundingClientRect()
      const systemInfo = uni.getSystemInfoSync()
      // 导航栏高度 = 胶囊高度 + 上下间距（胶囊到状态栏的距离 * 2）
      return menuButtonInfo.height + (menuButtonInfo.top - systemInfo.statusBarHeight) * 2
      // #endif
      // #ifdef H5
      return 0
      // #endif
    },
    open() {
      this.overflow = ''
    },
    close() {
      this.overflow = 'hidden'
    },
    toNotice() {
      uni.navigateTo({
        url: '/pages/notice/index'
      })
    },
    async initMap() {
      console.log('获取成功了定位')
      uni.showLoading({
        title: '加载中...'
      })
      if (this.location) {
        this.getList()
      } else {
        uni.getLocation({
          type: 'gcj02',
          success: res => {
            this.location = {
              latitude: res.latitude,
              longitude: res.longitude
            }
            // 如果没有地图中心点，初始化为当前位置
            if (!this.mapCenter) {
              this.mapCenter = { ...this.location }
            }
            this.getList()
          },
          fail: (err) => {
            console.log('获取位置失败：', err)
            uni.showToast({
              title: '获取位置失败，请检查定位权限',
              icon: 'none'
            })
            // 定位失败时跳转到城市选择页面
            uni.navigateTo({
              url: '/pages/city/index'
            })
          }
        })
      }
    },
    getList() {
      this.$api.getChargeStationList({
        pageNo: this.pageNo,
        pageSize: 10,
        city: this.currentCity.code ? this.currentCity.name : '',
        longitude: this.location.longitude,
        latitude: this.location.latitude,
        // 格式化请求参数
        ...this.searchForm
      }).then(res => {
        const { list } = res
        // 模拟充电站数据
        this.stations = list

        this.markers = this.stations.map(station => ({
          id: station.id,
          latitude: Number(station.lat),
          longitude: Number(station.lng),
          width: 38,
          height: 46,
          iconPath: '/static/map/station.png',
          // callout: {
          //   content: station.name,
          //   padding: 10,
          //   borderRadius: 5,
          //   display: 'ALWAYS'
          // }
        }))
        console.log(this.markers, 'markers')
        this.isShowMap = true
      }).finally(() => {
        uni.hideLoading()
      }).catch(() => {
        this.isShowMap = true
      })
    },
    handleSearch(e) {
      // 实现搜索功能
      console.log('搜索:', e.detail.value)
    },
    handleFilter(type) {
      // 实现筛选功能
      console.log('筛选类型:', type)
    },
    handleMarkerTap(e) {
      // 点击地图标记时显示充电站详情
      const station = this.stations.find(s => s.id === e.markerId)
      this.selectedStation = station
      console.log('selectedStation', this.selectedStation)
    },
    // 处理城市选择
    handleCitySelected(city) {
      this.selectedStation = false
      console.log('选择的城市:', city)
      this.currentCity = city

      // 使用腾讯地图WebService API进行地址解析
      uni.request({
        url: `/ws/geocoder/v1/?address=${encodeURIComponent(city.name)}&key=VQKBZ-WWSLG-EJQQI-IFK6O-E7CC6-N2BQE`,
        success: (res) => {
          console.log(res, 'res')
          if (res.data.status === 0) {
            const location = res.data.result.location
            // 更新地图中心点为选中的城市坐标
            this.mapCenter = {
              latitude: location.lat,
              longitude: location.lng
            }

            // 移动地图到新城市位置
            if (this.mapContext) {
              this.mapContext.moveToLocation({
                latitude: location.lat,
                longitude: location.lng,
                success: () => {
                  // 重新获取站点数据
                  this.initMap()
                }
              })
            } else {
              this.mapContext = uni.createMapContext('map', this)
              this.initMap()
            }
          } else {
            uni.showToast({
              title: '地址解析失败',
              icon: 'none'
            })
          }
        },
        fail: () => {
          uni.showToast({
            title: '地址解析请求失败',
            icon: 'none'
          })
        }
      })

      // 保存选择的城市到本地存储
      uni.setStorageSync('selectedCity', city)
    },
    changeCity() {
      uni.navigateTo({
        url: '/pages/city/index'
      })
    },
    toSearch() {
      uni.navigateTo({
        url: '/pages/search/index'
      })
    },
    zoomIn() {
      // 放大地图
      if (this.scale < 20) {
        this.scale++
      }
    },
    zoomOut() {
      // 缩小地图
      if (this.scale > 3) {
        this.scale--
      }
    },
    moveToLocation() {
      if (!this.mapContext) {
        this.mapContext = uni.createMapContext('map')
      }
      // 获取最新的当前位置
      uni.getLocation({
        type: 'gcj02',
        success: res => {
          // 更新用户当前位置
          this.location = {
            latitude: res.latitude,
            longitude: res.longitude
          }
          // 更新地图中心点为当前位置
          this.mapCenter = { ...this.location }

          // 获取当前位置的城市信息
          uni.request({
            url: `/ws/geocoder/v1/?location=${res.latitude},${res.longitude}&key=VQKBZ-WWSLG-EJQQI-IFK6O-E7CC6-N2BQE`,
            success: (geoRes) => {
              if (geoRes.data.status === 0) {
                const result = geoRes.data.result
                const currentCity = {
                  name: result.address_component.city,
                  code: result.ad_info.city_code
                }

                // 更新当前城市和缓存
                this.currentCity = currentCity
                uni.setStorageSync('selectedCity', currentCity)

                // 移动地图到当前位置并重新请求数据
                this.mapContext.moveToLocation({
                  latitude: res.latitude,
                  longitude: res.longitude,
                  success: (e) => {
                    console.log('移动到当前位置成功', e)
                    this.selectedStation = null // 重置选中的站点
                    this.initMap()
                  },
                  fail: (err) => {
                    console.log('移动到当前位置失败：', err)
                    uni.showToast({
                      title: '定位失败，请检查定位权限',
                      icon: 'none'
                    })
                  }
                })
              } else {
                uni.showToast({
                  title: '获取城市信息失败',
                  icon: 'none'
                })
              }
            },
            fail: () => {
              uni.showToast({
                title: '获取城市信息失败',
                icon: 'none'
              })
            }
          })
        },
        fail: (err) => {
          console.log('获取位置失败：', err)
          uni.showToast({
            title: '获取位置失败，请检查定位权限',
            icon: 'none'
          })
        }
      })
    },
    getCurrentLocation() {
      uni.getLocation({
        type: 'gcj02',
        success: res => {
          // 更新用户当前位置
          this.location = {
            latitude: res.latitude,
            longitude: res.longitude
          }

          // 如果没有地图中心点，初始化为当前位置
          if (!this.mapCenter) {
            this.mapCenter = { ...this.location }
          }
          // 逆向地理编码获取城市信息
          uni.request({
            url: `/ws/geocoder/v1/?location=${res.latitude},${res.longitude}&key=VQKBZ-WWSLG-EJQQI-IFK6O-E7CC6-N2BQE`,
            success: (geoRes) => {
              if (geoRes.data.status === 0) {
                const result = geoRes.data.result
                const currentCity = {
                  name: result.address_component.city,
                  code: result.ad_info.city_code
                }

                this.currentCity = currentCity
                uni.setStorageSync('selectedCity', currentCity)

                // 初始化地图并获取数据
                this.isShowMap = true
                this.$nextTick(() => {
                  this.mapContext = uni.createMapContext('map', this)
                  this.initMap()
                })
              }
            },
            fail: () => {
              uni.showToast({
                title: '城市信息获取失败',
                icon: 'none'
              })
            }
          })
        },
        fail: (err) => {
          console.log('获取位置失败：', err)
          uni.showToast({
            title: '获取位置失败，请检查定位权限',
            icon: 'none'
          })
          // 定位失败时跳转到城市选择页面
          uni.navigateTo({
            url: '/pages/city/index'
          })
        }
      })
    },
  }
}
</script>

<style scoped lang="scss">
.StationItem-box {
  position: fixed;
  bottom: 220rpx;
  left: 0;
  right: 0;
  z-index: 101;
  padding-left: -40rpx;
}
.container {
  width: 100%;
  height: 100vh;
  position: relative;
}

.search-header {
  background: #fff;
  position: fixed;
  width: calc(100% - 60rpx);
  z-index: 99;
  top: 160rpx;
  left: 30rpx;
  border-radius: 24rpx;
  .search-header-top {
    display: flex;
    align-items: center;
    padding: 40rpx;
    padding-bottom: 20rpx;
  }
}

.location {
  display: flex;
  align-items: center;
}

.search-box {
  flex: 1;
  background: #f5f5f5;
  border-radius: 20rpx;
  display: flex;
  align-items: center;
}

.search-box input {
  flex: 1;
  margin-left: 10rpx;
}

.message {
  margin-left: 20rpx;
  position: relative;
}

.badge {
  position: absolute;
  top: -10rpx;
  right: -10rpx;
  background: red;
  color: white;
  font-size: 20rpx;
  padding: 2rpx 8rpx;
  border-radius: 20rpx;
}

.map-container {
  width: 100%;
  height: 100vh;
  position: relative;
}

.map {
  width: 100%;
  height: 100vh;
}

.station-card {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: #fff;
  border-radius: 20rpx 20rpx 0 0;
  padding: 20rpx;
}

.station-image {
  width: 120rpx;
  height: 120rpx;
  border-radius: 10rpx;
}

.station-info {
  flex: 1;
  margin-left: 20rpx;
}

.station-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.station-status {
  color: #07c160;
}

.charger-info {
  display: flex;
  margin: 10rpx 0;
}

.charger-type {
  margin-right: 20rpx;
  padding: 4rpx 12rpx;
  border-radius: 4rpx;
  font-size: 24rpx;
}

.fast {
  background: #e1f3ff;
  color: #0091ff;
}

.slow {
  background: #fff0e5;
  color: #ff6b01;
}

.station-address {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: #666;
  font-size: 24rpx;
}

.location-btn {
  position: fixed;
  right: 32rpx;
  bottom: 240rpx;
  width: 80rpx;
  height: 80rpx;
  background: #FFFFFF;
  border-radius: 50%;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 100;

  image {
    width: 44rpx;
    height: 44rpx;
  }

  &:active {
    opacity: 0.8;
  }
}

.map-controls {
  position: fixed;
  right: 32rpx;
  bottom: 260rpx;
  display: flex;
  flex-direction: column;
  gap: 24rpx;
  z-index: 100;

  .control-btn {
    width: 80rpx;
    height: 80rpx;
    background: #FFFFFF;
    box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
    display: flex;
    align-items: center;
    justify-content: center;

    &:nth-child(1) {
      border-radius: 16rpx 16rpx 0 0;
      border-bottom: 1px solid #EEEEEE;
    }

    &:nth-child(2) {
      border-radius: 0 0 16rpx 16rpx;
      margin-top: -24rpx; // 抵消gap的间距
    }

    &:nth-child(3) {
      border-radius: 50%;
      margin-top: 0; // 恢复间距
    }

    image {
      width: 44rpx;
      height: 44rpx;
    }

    &:active {
      opacity: 0.8;
    }
  }
}
</style>
